package com.m3958.firstgwt.server.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.DbtplCacher;


import freemarker.template.Template;
import freemarker.template.TemplateException;

@Singleton
public class DbTplServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private Injector injector;
	
	
	@Inject
	private DbtplCacher tplCacher;
	
	@Inject
	private AppUtilService autils;
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String tplidStr = req.getRequestURI().split("/")[2];
		
		String want = Strings.emptyToNull(req.getParameter("want"));

		Template template = null;
		
		if(want == null){
			res.setContentType("text/html;charset=utf-8");
		}else{
			res.setContentType(want + ";charset=utf-8");
		}
		   
		res.setCharacterEncoding("UTF-8");
		Writer writer = res.getWriter();

		
		try {
			template = tplCacher.get(tplidStr);
		} catch (ExecutionException e1) {
			writer.write(e1.getStackTrace().toString());
			writer.flush();
			writer.close();
			return;
		} 
		
		
		Map<String, Object> rm = Maps.newHashMap();
		rm.put("requestParameters", getParameterMap(req));
		try {
			template.process(rm, writer);
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		writer.flush();
		writer.close();
	}

	private Object getParameterMap(HttpServletRequest req) {
		Map<String, String> maps = new HashMap<String, String>();
		@SuppressWarnings("unchecked")
		Map<String, String[]> m = req.getParameterMap();
		for(String s : m.keySet()){
			if(m.get(s).length == 1){
				maps.put(s, m.get(s)[0]);
			}
		}
		return maps;
	}
}
